#version 410

out vec4 FragColor;

struct DirectionLight 
{
	float ambientIntensity;
	float diffuseIntensity;
	float specularIntensity;
	float specularPower;
	vec3 direction;
	vec3 color;
};


uniform DirectionLight light;
uniform sampler2D shadowMap;
uniform sampler2D worldPosMap;
uniform sampler2D diffuseMap;
uniform sampler2D normalMap;
uniform vec2 screenSize;
uniform vec3 eyeWorldPos;

// Compute the linear fog factor
// This function gets the linear fog factor according to the linear fog equation..
// f = (fogEnd - depth) / (fogEnd - fogBegin)
// depth is calculated : dot(Normal of Camera, distance of fragment from camera)
float computeLinearFogFactor(vec3 worldPos, float near, float far)
{
	float factor;
	vec3 dVec = eyeWorldPos - worldPos;
	//vec3 norm = normalize(camNormal);

	//float dProd = abs(dot(dVec,norm));

	factor = (far - length(dVec) ) / (far - near);
	factor = clamp( factor, 0.0, 1.0 );
	return factor;
}

vec2 getTexCoord()
{
   return gl_FragCoord.xy / screenSize;
}

vec4 getLightInfluence(vec3 worldPos, vec3 norm)
{
	vec4 ambientColor = vec4(light.color, 1.0f) * light.ambientIntensity;
	float diffuseFactor = dot(norm, -light.direction);

	vec4 diffuseColor  = vec4(0, 0, 0, 0);
	vec4 specularColor = vec4(0, 0, 0, 0);

	if (diffuseFactor > 0) 
	{
		diffuseColor = vec4(light.color, 1.0f) * light.diffuseIntensity * diffuseFactor;
        vec3 vertexToEye = normalize(eyeWorldPos - worldPos);
        vec3 lightReflect = normalize(reflect(light.direction, norm));
        float specularFactor = dot(vertexToEye, lightReflect);
		specularFactor = pow(specularFactor, light.specularPower);
		if (specularFactor > 0)
		{
			specularColor = vec4(light.color, 1.0f) * light.specularIntensity * specularFactor;
		}
	}

	return ambientColor + diffuseColor + specularColor;
}

void main()
{
	vec2 texCoord = getTexCoord();
    vec4 worldPos = texture(worldPosMap, texCoord);
    vec4 color = texture(diffuseMap, texCoord);
    vec4 normal = texture(normalMap, texCoord);

	float fogFactor = computeLinearFogFactor(worldPos.xyz, 600, 1000);
	float fogDisFactor = computeLinearFogFactor(worldPos.xyz, 1000, 1005);

	vec4 fogColor =  vec4(0.784, 0.784,0.784, 1.0);
	vec4 lightFactor = getLightInfluence(worldPos.xyz, normal.xyz);

	color = color * lightFactor;
	color = vec4(color.rgb,1.0) * fogFactor + fogColor * (1.0 - fogFactor);

	FragColor = vec4(color.rgb, color.a * fogDisFactor);
}